﻿using System.Collections.Generic;
using System.Linq;
using CID.Domain.Operations;
using CID.Domain.Users;
using CID.Web.Models.Operations;
using CID.Web.Support;
using NailsFramework.IoC;
using NailsFramework.Persistence;

namespace CID.Web.Controllers
{
    [CIDAuthorize(UserRole.Manager, UserRole.EnvironmentManager)]
    public class ServerController : AjaxEnabledBaseCRUDController<IServer, Server, ServerViewModel>
    {
        #region Helper Members
        [Inject]
        public IBag<Location> Locations { private get; set; }
        
        [Inject]
        public IBag<ServerRole> ServerRoles { private get; set; }
        private IEnumerable<ServerRole> EnabledServerRoles { get { return ServerRoles.Where(x => x.Enabled); } }

        [Inject]
        public IBag<Environment> Environments { private get; set; }
        private IEnumerable<Environment> EnabledEnvironments { get { return Environments.Where(x => x.Enabled); } }
        #endregion

        protected override Server CreateModel(ServerViewModel viewModel)
        {
            return new Server(viewModel.Name, viewModel.Address, Locations.GetById(viewModel.LocationId));
        }

        protected override void PrepareViewModelForView(ServerViewModel viewModel)
        {
            base.PrepareViewModelForView(viewModel);

            viewModel.SetAvailableLocations(Locations);
            viewModel.SetAvailableEnvironments(EnabledEnvironments);
            viewModel.SetAvailableServerRoles(EnabledServerRoles);

            if (viewModel.LocationId.HasValue && string.IsNullOrEmpty(viewModel.Location))
                viewModel.Location = Locations.GetById(viewModel.LocationId.Value).Name;
        }
    }
}